package com.huika.renrench.control.main.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.AutoScrollViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.huika.lib.ui.widget.dialog.MMAlert;
import com.huika.lib.utils.MoneyShowTool;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseFra;
import com.huika.renrench.control.investment.activity.BookInvestActivity;
import com.huika.renrench.control.investment.activity.EarningsCalculateActivity;
import com.huika.renrench.control.investment.activity.ImmediatelyInvestActivity;
import com.huika.renrench.control.investment.activity.InvestmentGoActivity;
import com.huika.renrench.control.investment.activity.InvestmentRecordActivity;
import com.huika.renrench.control.login.activity.LoginActivity;
import com.huika.renrench.control.my.account.SetPayPwdActivity;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.AdvertisementInfo;
import com.huika.renrench.support.bean.ImageBean;
import com.huika.renrench.support.bean.InvestmentPoolBean;
import com.huika.renrench.utils.LoginUtils;
import com.huika.renrench.utils.WebNetUtils;
import com.huika.renrench.view.RoundProgressBar;
import com.huika.renrench.view.webview.BaseWebViewAct;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 
 * @description：投资
 * @author zc
 * @date 2015年6月3日 下午4:53:58
 */
public class InvestmentFragment extends BaseFra implements OnRefreshListener<ScrollView>, Listener<RequestResult<InvestmentPoolBean>> {

	private ImageView title_img;
	private TextView prompt;
	private TextView total_money_detail;
	private TextView numbers_detail;
	private TextView earnings_detail;
	private TextView lock_time_detail;
	private RoundProgressBar progress;
	private Button invest;
	private TextView tip_one;
	private TextView tip_two;
	private TextView tip_three;
	private TextView tip_four;
	private PullToRefreshScrollView scrollview_my;
	private InvestmentPoolBean bean;
	private DisplayImageOptions options;
	private TextView leave_balance;
	private int flag = -1;//1 可以立即投资  0 我要预约
	private View total_money_layout;
	private View numbers_layout;
	private String userId;
	private AutoScrollViewPager<AdvertisementInfo> shop_imgs;
	private View view;
	
	@Override
	protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.icon_default_big)
		// resource or drawable
		.showImageForEmptyUri(R.drawable.icon_default_big)
		.showImageOnFail(R.drawable.icon_default_big)
		.cacheInMemory(true)// 开启内存缓存
		.cacheOnDisk(true) // 开启硬盘缓存
		.resetViewBeforeLoading(true).build();
		userId = GlobalApp.getInstance().getUserId();
		view = inflater.inflate(R.layout.frag_investment, null, false);
		return view;
	}
	
	@Override
	protected void initWidget(View parentView) {
		super.initWidget(parentView);
		scrollview_my = (PullToRefreshScrollView) parentView.findViewById(R.id.scrollview_my);
		title_img = (ImageView) parentView.findViewById(R.id.title_img);
		prompt = (TextView) parentView.findViewById(R.id.prompt);
		total_money_detail = (TextView) parentView.findViewById(R.id.total_money_detail);
		numbers_detail = (TextView) parentView.findViewById(R.id.numbers_detail);
		earnings_detail = (TextView) parentView.findViewById(R.id.earnings_detail);
		lock_time_detail = (TextView) parentView.findViewById(R.id.lock_time_detail);
		progress = (RoundProgressBar) parentView.findViewById(R.id.progress);
		invest = (Button) parentView.findViewById(R.id.invest);
		tip_one = (TextView) parentView.findViewById(R.id.tip_one);
		tip_two = (TextView) parentView.findViewById(R.id.tip_two);
		tip_three = (TextView) parentView.findViewById(R.id.tip_three);
		tip_four = (TextView) parentView.findViewById(R.id.tip_four);
		leave_balance = (TextView) parentView.findViewById(R.id.leave_balance);
		total_money_layout = parentView.findViewById(R.id.total_money_layout);
		numbers_layout = parentView.findViewById(R.id.numbers_layout);
		shop_imgs = (AutoScrollViewPager<AdvertisementInfo>) parentView.findViewById(R.id.shop_imgs);
		shop_imgs.setScaleType(ScaleType.FIT_XY);
		shop_imgs.setImageOptions(new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.icon_default_small)
				// resource or drawable
				.showImageForEmptyUri(R.drawable.icon_default_small)
				.showImageOnFail(R.drawable.icon_default_small)
				.cacheInMemory(true)// 开启内存缓存
				.cacheOnDisk(true) // 开启硬盘缓存
				.resetViewBeforeLoading(false).build());
		setListner();
//		progress.setProgress(78);
//		getInvestPool(userId);
		executeGetAdvertisementInfoList(userId, 1);
	}
	
	private void initDatas(List<AdvertisementInfo> lists) {
		title_img.setVisibility(View.GONE);
		shop_imgs.refreshDatas(lists,
				(LinearLayout)(view.findViewById(R.id.advertisement_dotLl)), false, true);
		shop_imgs.start(3000);
	}

	private void setListner() {
		scrollview_my.setOnRefreshListener(this);
		total_money_layout.setOnClickListener(this);
		tip_one.setOnClickListener(this);
		tip_two.setOnClickListener(this);
		tip_three.setOnClickListener(this);
		tip_four.setOnClickListener(this);
		invest.setOnClickListener(this);
		numbers_layout.setOnClickListener(this);
	}
	
	@Override
	protected void widgetClick(View v) {
		super.widgetClick(v);
		Intent intent = null;
		if(bean != null) {
			
			switch (v.getId()) {
				case R.id.tip_four://常见问题
					intent = new Intent(getActivity(), BaseWebViewAct.class);
					intent.putExtra(BaseWebViewAct.PAGE_URL, WebNetUtils.getWebUrl("6"));
					intent.putExtra(BaseWebViewAct.PAGE_TITLE, "常见问题");
					intent.putExtra("left", "投资");
					break;
				case R.id.tip_three://收益计算器
					intent = new Intent(getActivity(), EarningsCalculateActivity.class);
					intent.putExtra("bean", bean);
					break;
				case R.id.tip_two://投资款去向
					intent = new Intent(getActivity(), InvestmentGoActivity.class);
					break;
				case R.id.tip_one://本息保障
					intent = new Intent(getActivity(), BaseWebViewAct.class);
					intent.putExtra(BaseWebViewAct.PAGE_URL, WebNetUtils.getWebUrl("3"));
					intent.putExtra(BaseWebViewAct.PAGE_TITLE, "本息保障");
					intent.putExtra("left", "投资");
					break;
				case R.id.invest://立即投资
					if(LoginUtils.isLogin()) {
						if(flag == 1) {
							if(GlobalApp.userModel.getIsSetPayPwd() == 0) {//没有设置交易密码提示
//								intent = new Intent(getActivity(), SetPayPwdActivity.class);
								warning();
								return;
							}
							intent = new Intent(getActivity(), ImmediatelyInvestActivity.class);
							intent.putExtra("investBalance", bean.getSpareAmount());
							intent.putExtra("startInvest", bean.getStartInvest());
						} else if(flag == 0) {
							intent = new Intent(getActivity(), BookInvestActivity.class);
							intent.putExtra("flag", 1);
						}
					} else {
						startActivity(new Intent(getActivity(), LoginActivity.class));
						return;
					}
//				intent = new Intent(getActivity(), BorrowDetailActivity.class);
					break;
				case R.id.total_money_layout:
					intent = new Intent(getActivity(), InvestmentGoActivity.class);
					break;
				case R.id.numbers_layout:
//					intent = new Intent(getActivity(), BaseWebViewAct.class);
//					intent.putExtra(BaseWebViewAct.PAGE_URL, WebNetUtils.getWebUrl("9"));
//					intent.putExtra("left", "投资");
//					intent.putExtra(BaseWebViewAct.PAGE_TITLE, "投资记录");
					intent = new Intent(getActivity(), InvestmentRecordActivity.class);
					break;
					
			}
			startActivity(intent);
		}
	}
	
	private void warning() {
		dialog = MMAlert.createShowCenterDialog(getActivity(), "温馨提示", "您未设置交易密码，请先设置", "忽略", "前往设置", null, new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showActivity(getActivity(), SetPayPwdActivity.class);
			}
		});
		dialog.show();
	}
	
	private Dialog dialog;
	
	private void getInvestPool(String userId) {
//		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		FormResultRequest<InvestmentPoolBean> request = new FormResultRequest<InvestmentPoolBean>(UrlConstants.GETPOOLINFO, this, this, new TypeToken<RequestResult<InvestmentPoolBean>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}

	@Override
	public void onRefresh(PullToRefreshBase<ScrollView> arg0) {
		getInvestPool(userId);
	}
	
	@Override
	public void onErrorResponse(VolleyError error) {
		super.onErrorResponse(error);
		scrollview_my.onRefreshComplete();
	}

	@Override
	public void onResponse(RequestResult<InvestmentPoolBean> arg0) {
		scrollview_my.onRefreshComplete();
//		dismissLoadingDialog();
		if(arg0.flag == 1 && arg0.getRs() != null) {
			bean = arg0.getRs();
			initViewData();
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		getInvestPool(userId);
	}

	private void initViewData() {
//		ImageLoader.getInstance().displayImage(bean.getImageUrl(),
//				title_img, options);
		prompt.setText(bean.getStartInvest() + "元起投,投资成功满一天开始计算收益");
		total_money_detail.setText(MoneyShowTool.nolastDF(Double.parseDouble(bean.getAmountTotal())) + "元");
		numbers_detail.setText(bean.getInvestCount() + "人");
		earnings_detail.setText(MoneyShowTool.twolastDF((Double.parseDouble(bean.getYearRate()) * 100d)) + "%");
		lock_time_detail.setText(bean.getLockDay() + "天");
		leave_balance.setText(MoneyShowTool.nolastDF(Double.parseDouble(bean.getSpareAmount())));
		float percent =  Float.parseFloat(bean.getSpareAmount()) / Float.parseFloat(bean.getAmountTotal());
		progress.setProgress((int) (100 - percent * 100));
		if(MoneyShowTool.nolastDF(Double.parseDouble(bean.getSpareAmount())).equals("0")) {
			flag = 0;
			invest.setText("我要预约");
		} else {
			flag = 1;
			invest.setText("立即投资");
		}
//		leave_balance.setText(MoneyShowTool.twolastDF(percent * 100) + "%");
	}
	
	/** 获取广告信息 */
	private void executeGetAdvertisementInfoList(String userId, int type) {
//		showLoadingDialog("加载中");
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("type", type);
		FormResultRequest<ArrayList<AdvertisementInfo>> request = new FormResultRequest<ArrayList<AdvertisementInfo>>(UrlConstants.GETADVERTISEMENTINFO,
				getAdvertisementInfoListReq, this, new TypeToken<RequestResult<ArrayList<AdvertisementInfo>>>() {
				}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	
	private Listener<RequestResult<ArrayList<AdvertisementInfo>>> getAdvertisementInfoListReq = new Listener<RequestResult<ArrayList<AdvertisementInfo>>>() {

		@Override
		public void onResponse(RequestResult<ArrayList<AdvertisementInfo>> result) {
			dismissLoadingDialog();
			if (result != null && result.flag == 1 && result.getRs().size() > 1) {
				title_img.setVisibility(View.GONE);
//				advertisementVp.refreshDatas(result.getRs(), advertisement_dotLl, false, true);
//				advertisementVp.start(3000);
				
				initDatas(result.getRs());
			} else if(result != null && result.flag == 1 && result.getRs().size() == 1){
				title_img.setVisibility(View.VISIBLE);
				ImageLoader.getInstance().displayImage(result.getRs().get(0).getImageUrl(),
						title_img, options);
			}

		}
	};
	
	private String handleMoney(String money) {
		String newStr = MoneyShowTool.nolastDF(Double.parseDouble(money));
		StringBuffer sb = new StringBuffer();
		int count = newStr.length() / 3;
		int count2 = newStr.length() % 3;
		if(count <= 1) {
			return newStr;
		}
		switch (count2) {
			case 0:
				sb.append(newStr.substring(0, 3));
				count2 = 3;
				break;
			case 1:
				sb.append(newStr.substring(0, 1));
				count2 = 1;
				break;
			case 2:
				sb.append(newStr.substring(0, 2));
				count2 = 2;
				break;

			default:
				break;
		}
		sb.append(",");
		for(int i = 0; i < count - 1; i++) {
			if(count2 !=3 || i != count - 1) {
				sb.append(newStr.substring(count2 + 3 * i, count2 + 3 * i  + 3));
				sb.append(",");
			}
		}
		return sb.substring(0, sb.length() - 1);
	}

}
